package com.control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.htree.HTree;

public class JDBManager {

	private RecordManager recordManager;
	private long recordId;

	// create or open record manager
	public JDBManager(String dbName) throws IOException {

		recordManager = RecordManagerFactory.createRecordManager(dbName);

	}

	public HTree loadHashTable(String tableName) throws IOException {
		HTree hashTable;
		recordId = recordManager.getNamedObject(tableName);
		if (recordId != 0) {
			hashTable = HTree.load(recordManager, recordId);
		} else {
			hashTable = HTree.createInstance(recordManager);
			recordManager.setNamedObject(tableName, hashTable.getRecid());
		}
		return hashTable;
	}

	public void buildValidator(ArrayList<?> keys, HTree hashTable)
			throws IOException {
		for (int i = 0; i < keys.size(); i++) {
			hashTable.put(keys.get(i), i);
		}
	}

	public void buildHashTable(ArrayList<?> values, HTree hashTable)
			throws IOException {
		for (int i = 0; i < values.size(); i++) {
			hashTable.put(i, values.get(i));
		}
	}

	public void buildHashTable(HashMap<?, ?> values, HTree hashTable)
			throws IOException {
		for (Object key : values.keySet()) {
			insert(key, values.get(key), hashTable);
		}
	}

	public void insert(Object key, Object value, HTree hashTable)
			throws IOException {
		hashTable.put(key, value);
	}

	public void insertAll(ArrayList<?> keys, ArrayList<?> values,
			HTree hashTable) throws IOException {
		for (int i = 0; i < keys.size(); i++) {
			insert(keys.get(i), values.get(i), hashTable);
		}
	}

	// commit all the changes
	public void commit() throws IOException {
		recordManager.commit();
	}

	// close the record manager
	public void close() throws IOException {
		recordManager.close();
	}

}
